package com.qzdatasoft.autoconfigure.mcp.server;

import com.qzdatasoft.mcp.server.common.JdbcTemplateInterceptor;
import com.qzdatasoft.mcp.server.mysql.service.MySqlToolService;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.ObjectUtils;

import java.util.Map;
import java.util.Objects;

@AutoConfiguration
public class MysqlMcpServerConfiguration {

	@Bean
	public JdbcTemplateInterceptor.JdbcPermission dbHelper(ObjectProvider<JdbcTemplate> jdbcTemplate) {
		checkProvider(jdbcTemplate,"jdbcTemplate");
		return new JdbcTemplateInterceptor.JdbcPermission() {
			@Override
			public Map<String, String[]> getRoles() {
				return Map.of(
						"readonly", new String[]{"SELECT", "SHOW", "DESCRIBE", "EXPLAIN"},  // 只读权限
						"writer", new String[]{"SELECT", "SHOW", "DESCRIBE", "EXPLAIN", "INSERT", "UPDATE", "DELETE"}, // 读写权限
						"admin", new String[]{"SELECT", "SHOW", "DESCRIBE", "EXPLAIN", "INSERT", "UPDATE", "DELETE", "CREATE", "ALTER", "DROP", "TRUNCATE"}  // 管理员权限
				);
			}

			@Override
			public String getCurrentDbType() {
				return "mysql";
			}

			@Override
			public JdbcTemplate getJdbcTemplate() {
				return jdbcTemplate.getIfAvailable();
			}
		};
    }

	@Bean
	public MySqlToolService mySqlToolService(ObjectProvider<JdbcTemplate> jdbcTemplate) {
		checkProvider(jdbcTemplate,"jdbcTemplate");
		return new MySqlToolService(Objects.requireNonNull(jdbcTemplate.getIfAvailable()));
	}

	private void checkProvider(ObjectProvider<?> provider,  String beanName){
		if(ObjectUtils.isEmpty(provider.getIfUnique()) || ObjectUtils.isEmpty(provider.getIfAvailable())){
			throw new IllegalArgumentException("请检查是否配置了%s.".formatted(beanName));
		}
	}

}
